#!/usr/bin/sh

# 定义app\key\tag(river tag)
hi_apps=('r' 't' 'lf' 'g' 'nvim' 'qutebrowser' 'y' 'u' 'waydroid show-full-ui' 'wps' 'virt-manager' 'ncmpcpp' 'blender')
foot_apps=('lf' 'nvim' 'ncmpcpp' 'fastfetch')
hi_keys=('r' 't' 'f' 'g' 'v' 'b' 'y' 'u' 'i' 'o' 'p' 'm', '3')
hi_tags=(1 2 3 4 5 6 7 8 9 10 11 12 13)
term="footclient"

# 判断函数
array_contains() {
  local target="$1"
  shift
  local array=("$@")

  for item in "${array[@]}"; do
    if [[ "$item" == "$target" ]]; then
      return 0 # 找到，返回成功
    fi
  done
  return 1 # 没找到，返回失败
}

# switch & run app
riverctl_run() {
  local keymask="$1"
  shift
  local cmd=("$@")

  for item in "${cmd[@]}"; do
    riverctl $item $keymask
  done

  riverctl focus-view next # 无法跨tag,但是只要在同一个tag中，就能
}

# 定义 key、app、tag  ; cmd: riverctl param
cmd=('set-focused-tags')
app=''
key=''
tag=1
tag_mask=1 # tag_mask(riverctl 能够识别的tag码)
#
# 根据key找到app、tag
for i in "${!hi_keys[@]}"; do
  if [ "+"${hi_keys[$i]} = $1 ]; then
    app=${hi_apps[$i]}
    key=${hi_keys[$i]}
    tag=${hi_tags[$i]}

    cmd=('toggle-focused-tags')
    break
  fi

  if [ ${hi_keys[$i]} = $1 ]; then
    app=${hi_apps[$i]}
    key=${hi_keys[$i]}
    tag=${hi_tags[$i]}
    break
  fi
done

# 检查该应用是否在我们的映射表中
if [[ -n "${tag}" ]]; then
  # 计算标签的位掩码，RiverWM 使用位掩码操作标签
  tag_mask=$((1 << (tag - 1)))
  echo $tag_mask
  echo "${cmd[@]}"
else
  dunstify -t 1500 -u normal "Application '${app}' not found in the mapping."
fi

# 检查无参应用是否已经在运行
if pgrep -x "$app" >/dev/null || pgrep -xf "$term -T $app" >/dev/null; then
  # 应用已在运行，只切换标签
  echo "之前已运行$app"

  if array_contains $app "${foot_apps[@]}"; then
    echo "在foot组中"
    riverctl_run $tag_mask "${cmd[@]}"

    if pgrep -xf "$term $app" >/dev/null; then
      echo "之前已运行$term $app"
    else
      riverctl spawn "$term $app" &
    fi

  else
    echo "不在foot组中"
    riverctl_run $tag_mask "${cmd[@]}"
  fi

  dunstify -t 1500 -u normal "${app} switch complete"
else
  # 应用未运行，启动应用并切换标签
  riverctl_run $tag_mask "${cmd[@]}"
  dunstify -t 1500 -u normal "${app} bootting"

  if array_contains $app "${foot_apps[@]}"; then
    echo "在组中"
    riverctl spawn "$term $app" &
  else
    echo "不在组中"
    if [ ${#app} -eq 1 ]; then
      echo "字符串只有一个字符，默认执行 footclient -T $app"
      riverctl spawn "$term -T $app"
    else
      echo "字符串有多个字符或为空"
      riverctl spawn "$app"
    fi
  fi

  dunstify -t 1500 -u normal "${app} booted"
fi
